﻿using System;
using System.Collections.Generic;

namespace Petra.Gis.RenderingServices.PlanarBase 
{
  /// <summary>
  /// represents legend node that can contain renderable legend nodes
  /// this is the only objects that can add new item into (or remove from) map legend
  /// </summary>
  public class LeafLegendNode : LegendNode
  {

    protected List<LegendNode> _childNodes;
    protected LegendChildNodes _childs;
    protected List<LegendNode> _displayOrderList;


    public LeafLegendNode(LegendNode parent, string title)
      :base(null, title)
    {

      _nodeType = LegendNodeType.GroupNode;
      _childNodes = new List<LegendNode>();
      _childs = new LegendChildNodes(this, _childNodes);

      //get display order list instance reference from parent object
      _displayOrderList = ((LeafLegendNode)parent)._displayOrderList;
    }



    public LegendChildNodes ChildNodes
    {
      get { return _childs; }
    }




    public LegendNode InsertNode(LegendNode newChild)
    {
      if (_nodeType != LegendNodeType.GroupNode)
        throw new InvalidOperationException("invalid command");

      //if parent of newChild is not null then remove it from prev
      if (newChild.Parent != null)
        //reinsert existing node into another place
        //display order remains same
        //so must use removeNode instead of RemoveNode
        ((LeafLegendNode)newChild.Parent).removeNode(newChild);
      else
        //new node insert, put into displayOrder collection
        _displayOrderList.Insert(0, newChild);

      //add to current collection
      _childNodes.Add(newChild);
      newChild.Parent = this;
      return newChild;
    }



    /// <summary>
    /// removes node complettely from all collection
    /// </summary>
    /// <param name="childToRemove"></param>
    /// <returns>removed node instance</returns>
    public LegendNode RemoveNode(LegendNode childToRemove)
    {
      _childNodes.Remove(childToRemove);
      _displayOrderList.Remove(childToRemove);
      return childToRemove;
    }



    /// <summary>
    /// removes node only from _childNodes collection
    /// and leaves it in _displayOrder ;-)
    /// </summary>
    /// <param name="childToRemove"></param>
    /// <returns></returns>
    protected LegendNode removeNode(LegendNode childToRemove)
    {
      _childNodes.Remove(childToRemove);
      return childToRemove;
    }




    public override void RenderData()
    {
      //leaf does nothing ;-)
    }


  }
}
